/** 
 * FontSelectorButton.java
 * @author Lex
 * 2007-9-8 ����02:45:32
 */
package org.lex.swing.widgets;

import java.awt.Font;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;

import javax.swing.JButton;
import javax.swing.SwingUtilities;

import org.lex.swing.fontchooser.JFontChooser;
import org.lex.utils.Codec;


public class FontSelectorButton extends JButton {
	public static final String SELECTED_FONT_CHANGED_PROPERTY = "selectedFontChangedProperty";
	private static final String DEFAULT_TITLE = "Font";
	// =================================================
	private Font selectedFont = null;
	private String dialogTitle = DEFAULT_TITLE;

	public FontSelectorButton() {
		this(DEFAULT_TITLE);
	}

	public FontSelectorButton(String title) {
		this(null, title);
	}

	public FontSelectorButton(Font font, String title) {
		super();
		this.dialogTitle = title;
		this.setSelectedFont(font, false);
		this.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Font font = JFontChooser.showDialog(root(), dialogTitle, selectedFont);
				if (null == font)
					return;
				setSelectedFont(font);
			}

			private Window root() {
				return SwingUtilities.getWindowAncestor(FontSelectorButton.this);
			}
		});
	}

	public void setSelectedFont(Font font) {
		this.setSelectedFont(font, true);
	}

	public void setSelectedFont(Font font, boolean fireEvent) {
		Font old = this.selectedFont;
		this.selectedFont = font;
		if (null == font)
			return;
		super.setText(Codec.displayFont(font));
		super.setFont(font);
		if (true == fireEvent)
			firePropertyChange(SELECTED_FONT_CHANGED_PROPERTY, old, font);
	}

	/**
	 * 
	 * @return selected font, or return null if nothing selected
	 */
	public Font getSelectedFont() {
		return this.selectedFont;
	}

	public void addFontChangeListener(PropertyChangeListener l) {
		super.addPropertyChangeListener(SELECTED_FONT_CHANGED_PROPERTY, l);
	}

	public void removeFontChangeListener(PropertyChangeListener l) {
		super.removePropertyChangeListener(SELECTED_FONT_CHANGED_PROPERTY, l);
	}
}
